# -*- coding: utf-8 -*-
import time
import win32gui, win32ui, win32con,win32api
import pytesseract
from PIL import Image
import webbrowser
import base64
import requests

image_path = 'D:/py_study/question/jietu.jpg'
api_url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic' 
data = {}  
data['access_token']='24.99251c898e73d20654644d70dd558cf1.2592000.1525103276.282335-11028562'

#截图
def window_capture(filename):
    w = 311
    h = 248
    x = 94
    y = 200
    hwnd = 0
    hwndDC = win32gui.GetWindowDC(hwnd)
    mfcDC = win32ui.CreateDCFromHandle(hwndDC)
    saveDC = mfcDC.CreateCompatibleDC()
    saveBitMap = win32ui.CreateBitmap()
    #获取监视器信息
    MoniterDev = win32api.EnumDisplayMonitors(None, None)
    # w = MoniterDev[0][2][2]
    # h = MoniterDev[0][2][3]
    saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
    saveDC.SelectObject(saveBitMap)
    saveDC.BitBlt((0, 0), (w, h), mfcDC, (x, y), win32con.SRCCOPY)
    saveBitMap.SaveBitmapFile(saveDC, filename)

def get_text():

    file=open('jietu.jpg','rb')  
    image= file.read()  
    file.close()  

    data['image'] = base64.b64encode(image)  
    headers={
        "Content-Type":"application/x-www-form-urlencoded",
        "apikey":"bN7UbbadGNuM00S5v1B0cP6H"
    }
    res = requests.post(url=api_url,headers=headers,data=data)
    result = res.json()
    return result

if __name__ == '__main__':
    #方法一
    begin = time.time()
    #window_capture('jietu.jpg')
    # image = Image.open(image_path)
    # text = pytesseract.image_to_string(image,lang='chi_sim')
    #方法二
    result = get_text()
    text = result['words_result'][0]['words']
    end = time.time()
    print(text)
    print('耗时：' + str(end-begin))
    url = 'http://www.baidu.com/s?wd=%s' % text
    webbrowser.open(url)
